package contest.oop.sse.secalg;

/**
 * 异或算法
 *
 * @author paule
 */
public class XorAlgorithm extends SymmetricAlgorithm {
    public XorAlgorithm() {}

    public XorAlgorithm(String key) {
        this.key = key;
    }

    @Override
    public byte[] encrypt(String original) {
        String messageStr = original.toString();
        byte[] cipher = new byte[messageStr.length()];
        for (int i = 0; i < messageStr.length(); i++) {
            cipher[i] = (byte) (messageStr.charAt(i) ^ key.charAt(0));
        }
        return cipher;
    }

    @Override
    public String decrypt(byte[] cipher) {
        StringBuilder builder = new StringBuilder();
        for (byte b: cipher) {
            builder.append((char) (b ^ key.charAt(0)));
        }
        return builder.toString();
    }
}
